<template>
    <div class="app-container bg-grey">

      <div v-show="showSearch">
        <el-row :gutter="12" class="bg-fff bor-r-10 p20 mb20">
          <el-col :span="1.5" v-for="dict in threadType">
            <el-tag class="tagQueryBtn link warnning"
            :class="queryP.metadata.type == dict.value ? 'tagQueryBtnActive link warnning' : ''"
            type="info" @click="upQuery('type',dict.value,isMeta=true)" color="rgba(0,0,0,0)"><span class="icon iconfont" :class="dict.icon" style="margin-right:5px;"></span><span style="position: relative;top:-2px;">{{ dict.label }}</span></el-tag>
          </el-col>
          <el-col :span="1.5" v-for="dict in threadStatus">
            <el-tag class="tagQueryBtn"
            :class="queryP.status == dict.value ? 'tagQueryBtnActive' : ''"
            type="info" @click="upQuery('status',dict.value)" color="rgba(0,0,0,0)"><span class="icon iconfont" :class="dict.icon" style="margin-right:5px;"></span><span style="position: relative;top:-2px;">{{ dict.label }}</span></el-tag>
          </el-col>
          <el-col :span="1.5" class="right">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>
      </div>

      <div class="h45">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
  
      <el-row :gutter="12" class="bg-fff bor-r-10 p20 mb110">

      <el-table v-loading="loading" :data="threadList" @selection-change="handleSelectionChange" stripe>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标题" align="center" prop="metadata">
          <template slot-scope="scope">
            {{ scope.row.metadata.ques }}
          </template>
        </el-table-column>
        <el-table-column label="关联设备" align="center" prop="metadata">
          <template slot-scope="scope">
            {{ scope.row.metadata.uuid }}
          </template>
        </el-table-column>
        <el-table-column label="线程ID" align="center" prop="thread_id" />
        <!-- <el-table-column label="名称" align="center" prop="name" /> -->
        <!-- <el-table-column label="数据Key" align="center" prop="config.configurable.collection_name" /> -->
        <!-- <el-table-column label="graphId" align="center" prop="graph_id" /> -->
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="threadStatus" :value="scope.row.status"/>
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" align="center" prop="created_at" width="260"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-chat-round"
              @click="handleUpdate(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-row>

      <div class="bg-grey page-posi-div" v-show="total>0">
        <div class="bg-fff bor-r-10 p10 pb20">
          <pagination
          :total="total"
          :page.sync="queryP.pageNum"
          :limit.sync="queryP.limit"
          @pagination="getList"
          />
        </div>
      </div>
  
      <el-drawer v-if="open"
        :title="title"
        direction="ltr"
        :visible.sync="open"
        :before-close="cancel" size="80%">
        <div class="p20">

          <el-descriptions title="对话信息" direction="vertical" :column="2" border>
            <el-descriptions-item label="对话标题" :span="2" v-if="form.metadata.ques">{{ form.metadata.ques }}</el-descriptions-item>
            <el-descriptions-item label="关联数据">{{ form.metadata.key }}</el-descriptions-item>
            <el-descriptions-item label="对话设备" >{{ form.metadata.uuid }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ form.created_at }}</el-descriptions-item>
            <el-descriptions-item label="上次时间">{{ form.updated_at }}</el-descriptions-item>
          </el-descriptions>
          <el-divider>对话记录</el-divider>
          <div style="height: calc(100vh - 460px);border-radius: 15px;background: rgba(243,243,243,0.7);overflow-y: auto;
          box-shadow: inset  0 0 5px rgba(0,0,0,0.05);padding:20px;border:1px solid rgba(0,0,0,0.05);">
            <div class="message-item" :class="message.type" v-for="message in form.values.messages">
              <div class="message-bubble">
                <div class="message-text" v-html="upContent(message.content)"></div>
              </div>
            </div>
          </div>

        </div>

      </el-drawer>
     
    </div>
  </template>
  
  <script>
  import langC from "@/api/wenda/langChain";
  import markdown from '@/utils/wenda/markdown.js'; // 引入定义样式后的markdown

  export default {
    name: "Post",
    data() {
      return {
        threadStatus:[{value:'idle',label:"空闲",icon:"icon-kongxian",raw:{listClass:'primary'}},{value:'busy',label:"忙碌",icon:"icon-mangluxian",raw:{listClass:'warning'}},{value:'interrupted',label:"中断",icon:"icon-caozuozhongduan",raw:{listClass:'info'}},{value:'error',label:"错误",icon:"icon-cuowu",raw:{listClass:'error'}}],
        threadType:[{value:'user',label:"用户",icon:"icon-yonghu",raw:{listClass:'primary'}},{value:'links',label:"联动",icon:"icon-a-daping",raw:{listClass:'warning'}}],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        threadList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryP: {
            pageNum:1,
            offset: 0,
            limit: 10,
            status: "idle",
            metadata: {type:"user"},
        },
        // 表单参数
        form: {},
        isDis :false,
        // 表单校验
        rules: {
            name: [
              { required: true, message: "名称不能为空", trigger: "blur" }
            ]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 格式化返回内容
      upContent(text) {
        if (text) {
          return markdown.returnContent(text.replace('并且以中文回复，回复内容中不包含附件参考信息', ''))
        }
      },
      upQuery(key,val,isMeta=false){
        if(isMeta){
          this.queryP.metadata[key] = val
        }else{
          this.queryP[key] = val
        }
        this.getList();
      },
      /** 查询岗位列表 */
      getList() {
        this.loading = true;
        let q = {...this.queryP}
        this.queryP.offset = (this.queryP.pageNum-1)*this.queryP.limit
        // if(this.queryP.ques){
        //   this.queryP.metadata.ques = this.queryP.ques
        // }
        langC.threadList(this.queryP).then(res => {
            this.threadList = res
            this.loading = false;
        });
        q.limit = 999
        q.offset = 0
        langC.threadList(q).then(res => {
            this.total = res.length
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.isDis =!1
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
        };
        this.isDis =!1
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.names = selection.map(item => item.name)
        this.ids = selection.map(item => item.thread_id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.isDis =!1
        this.title = "添加线程";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.thread_id || this.thread_id
        langC.threadGet(id).then(res => {
          res.configStr = JSON.stringify(res.config)
          res.metadataStr = JSON.stringify(res.metadata)
          res.valuesStr = JSON.stringify(res.values)
          this.form = res;
          console.log("修改按钮操作",this.form )
          this.open = true;
          this.title = res.metadata.ques
        });
      },

      /** 删除按钮操作 */
      async handleDelete(row) {
        console.log(row)
        const id = row.thread_id
        console.log(this.ids)
        const names = this.ids.length ? '是否确认删除' + this.ids.length + '个数据项？' : '是否确认删除标题为"' + row.metadata.ques + '"的数据项？'

        this.$modal.confirm(names).then(() => {
            if(this.ids.length){
                for (let i = 0; i < this.ids.length; i++) {
                    console.log(this.ids[i])
                    langC.threadDelete(this.ids[i]);
                }
                return true
            }else{
                
                langC.threadDelete(id);
            }
        }).then(() => {
            this.$modal.msgSuccess("删除成功");
            setTimeout(() => {
                this.getList();
            }, 1000);
        }).catch(() => {});
      },
    }
  };
  </script>
  
<style scoped>
/* 对话框 */
.message-item {
  margin-bottom: 5px;
}

.message-bubble {
  max-width: 80%;
  overflow: hidden;
  padding: 10px 16px;
  border-radius: 20px;
  position: relative;
  box-shadow: rgba(100, 100, 100, 0.1) 2px 3px 5px;
}
.message-item.human {
  display: flex;
  flex-direction: row-reverse;
}
.message-item.human .message-bubble {
  background: rgb(110, 177, 248);
  color: white;
  padding: 3px 16px 2px;
  margin-right: 10px;
}

.message-item.ai .message-bubble  {
  background: white;
  border: 1px solid #ebeef5;
}
</style>
